package com.party.admin.web.controller.operation;

import com.party.admin.biz.article.ArticleBizService;
import com.party.admin.biz.file.FileBizService;
import com.party.admin.biz.serviceguide.ServiceGuideBizService;
import com.party.admin.biz.system.MemberBizService;
import com.party.admin.utils.RealmUtils;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.input.common.CommonInput;
import com.party.admin.web.dto.output.article.ArticleOutput;
import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.BaseModel;
import com.party.core.model.YesNoStatus;
import com.party.core.model.article.Article;
import com.party.core.model.article.ArticleMember;
import com.party.core.model.article.ArticleType;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.serviceguide.ServiceGuideRelation;
import com.party.core.model.serviceguide.ServiceGuideType;
import com.party.core.model.system.Dict;
import com.party.core.model.system.DictEnum;
import com.party.core.service.article.IArticleMemberService;
import com.party.core.service.article.IArticleService;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.serviceguide.IServiceGuideRelationService;
import com.party.core.service.serviceguide.IServiceGuideTypeService;
import com.party.core.service.system.IDictService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

/**
 * 服务指南
 *
 * @author huangwuming
 * on 2018/6/17
 */
@Controller
@RequestMapping(value = "/service/article")
public class ServiceArticleController {

    @Autowired
    private IArticleService articleService;

    @Autowired
    private IDictService dictService;

    @Autowired
    private FileBizService fileBizService;

    @Autowired
    private ArticleBizService articleBizService;

    @Autowired
    private CosBizService cosBizService;

    @Autowired
    private MemberBizService memberBizService;

    @Autowired
    private IArticleMemberService articleMemberService;

    @Autowired
    private IMemberGroupService memberGroupService;

    @Autowired
    private ServiceGuideBizService serviceGuideBizService;

    @Autowired
    private IServiceGuideTypeService serviceGuideTypeService;

    @Autowired
    private IServiceGuideRelationService serviceGuideRelationService;

    protected static Logger logger = LoggerFactory.getLogger(ServiceArticleController.class);


    /**
     * 文章管理
     *
     * @param article
     * @param page
     * @param commonInput
     * @return
     */
    @RequestMapping(value = "list")
    public ModelAndView articleList(Article article, Page page, CommonInput commonInput) {
        ModelAndView mv = new ModelAndView("operation/service/articleList");

        article.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        article.setArticleType(ArticleType.ARTICLE_TYPE_SERVICE.getCode());
        Map<String, Object> params = CommonInput.appendParams(commonInput);

        mv.addObject("input", commonInput);

        List<ServiceGuideType> serviceGuideTypes = serviceGuideBizService.getServiceGuideTypeAll();

        List<Article> articles = articleService.webListPage(article, params, page);
        List<ArticleOutput> articleOutputs = LangUtils.transform(articles, input -> {
            ArticleOutput articleOutput = ArticleOutput.transform(input);
            String articleType = input.getArticleType();
            Dict dict = new Dict();
            dict.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
            dict.setType(DictEnum.ARTICLE_TYPE.getCode());
            dict.setValue(articleType);
            Dict dictEntity = dictService.getByProperty(dict);
            if (dictEntity != null) {
                articleOutput.setArticleType(dictEntity.getLabel());
            }
            String filePath = fileBizService.getUploadCIPath(input.getMemberId(), "article");
            // 详情二维码
            String fileName = "detail_" + input.getId();
            String qrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + fileName);
            articleOutput.setQrCodeUrl(qrCodeUrl);
            return articleOutput;
        });
        mv.addObject("articles", articleOutputs);
        mv.addObject("serviceGuideTypes", serviceGuideTypes);
        mv.addObject("page", page);
        return mv;
    }

    /**
     * 服务指南-发布/编辑文章
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "serviceArticleForm")
    public ModelAndView articleForm(String id) {
        ModelAndView mv = new ModelAndView("operation/service/serviceArticleForm");
        // 文章类型
        Dict dict = new Dict();
        dict.setType(DictEnum.ARTICLE_TYPE.getCode());
        mv.addObject("types", dictService.list(dict));

        //指南类型
        List<ServiceGuideType> serviceGuideTypes = new ArrayList<>();

        // 文章
        if (StringUtils.isNotEmpty(id)) {
            Article article = articleService.get(id);
            String content = StringUtils.unescapeHtml4Video2Iframe(article.getContent());
            article.setContent(content);
            mv.addObject("article", article);

            if (article.getIsShowAll().equals(YesNoStatus.NO.getCode())) {
                ArticleMember query = new ArticleMember();
                query.setArticleId(article.getId());
                List<ArticleMember> articleMembers = articleMemberService.list(query);
                List<String> memberIdList = LangUtils.transform(articleMembers, input -> input.getMemberId());
                List<MemberGroup> members = memberGroupService.batchList(new HashSet<>(memberIdList), null, null);
                mv.addObject("members", members);
            }
            //获取指南类型列表
            serviceGuideTypes = serviceGuideTypeService.querySGRListbysgId(article.getId());
        }

        mv.addObject("categoryList", serviceGuideTypes);
        return mv;
    }


    /**
     * 服务指南文章保存
     *
     * @param article
     * @param result
     * @param members
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "save")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult save(Article article, BindingResult result, String members) {
        String memberId = RealmUtils.getCurrentUser().getId();
        // 数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErros = result.getAllErrors();
            return AjaxResult.error(allErros.get(0).getDefaultMessage());
        }

        try {

            try {
                serviceGuideBizService.updateGoodsNum("update",article.getId(),article.getCategoryList());
            }catch (Exception e){
                logger.error("更新指南类型统计数异常", e);
            }

            articleBizService.saveOrupdateArticle(article,members,memberId);

            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("保存文章异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("保存文章异常");
        }
    }

    /**
     * 删除文章
     */
    @ResponseBody
    @RequestMapping(value = "delete")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult delete(String id) {
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error("id不能为空");
        }
        try {
            //更新统计数
            try {
                serviceGuideBizService.updateGoodsNum("delete", id, "");
            } catch (Exception e) {
                logger.error("更新分类统计数异常", e);
            }

            articleService.delete(id);
            articleBizService.deleteArticleMember(id);
            serviceGuideRelationService.deleteSGR(new ServiceGuideRelation(id, null));
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("文章删除异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("文章删除异常");
        }
    }

    /**
     * @return
     * @Author yifeng
     * @Description 删除标记为全部的文章的和用户的关系
     * @Date 11:29 2019/5/6
     **/
    @ResponseBody
    @RequestMapping(value = "deleteArticleMember")
    public AjaxResult deleteArticleMember() {
        try {
            Article article = new Article();
            article.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
            article.setArticleType(ArticleType.ARTICLE_TYPE_SERVICE.getCode());
            article.setIsShowAll(YesNoStatus.YES.getCode());
            List<Article> articleList = articleService.list(article);
            for (Article query : articleList) {
                articleMemberService.deleteByArticleId(query.getId());
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("删除文章和机构的关系异常", e);
            return AjaxResult.error("删除异常");
        }
    }
}
